﻿using EP.Core.Data;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EP.Entities
{
    public class EFRepository<TEntity> : IRepository<TEntity> where TEntity : class
    {
        private Task nullTask = new Task(()=>{});
        private GeneralDbContext _dbContext;
        public EFRepository(GeneralDbContext generalDbContext)
        {
            this._dbContext = generalDbContext;
        }
        public DbContext DbContext
        {
            get
            {
                return _dbContext;
            }
        }
        public DbSet<TEntity> Entities
        {
            get
            {
                return _dbContext.Set<TEntity>();
            }
        }
        public IQueryable<TEntity> Table
        {
            get
            {
                return Entities;
            }
        }
        public void Delete(TEntity entity, bool isSave = true)
        {
            Entities.Remove(entity);
            if (isSave) 
                SaveChanges();
        }
        public Task DeleteAsync(TEntity entity, bool isSave = true)
        {
            Entities.Remove(entity);
            if (isSave) 
                return SaveChangesAsync();
            return nullTask;
        }
        public TEntity GetById(object id)
        {
            return Entities.Find(id);
        }
        public ValueTask<TEntity> GetByIdAsync(object id)
        {
            return Entities.FindAsync(id);
        }
        public void Insert(TEntity entity, bool isSave = true)
        {
            Entities.Add(entity);
            if (isSave)
                SaveChanges();
        }
        public Task InsertAsync(TEntity entity, bool isSave = true)
        {
            Task.WhenAll(Entities.AddAsync(entity).AsTask());
            if (isSave)
                return SaveChangesAsync();
            return nullTask;
        }

        public int SaveChanges()
        {
            return _dbContext.SaveChanges();
        }

        public Task<int> SaveChangesAsync()
        {
            return _dbContext.SaveChangesAsync();
        }

        public void Update(TEntity entity, bool isSave = true)
        {
            if (isSave)
                _dbContext.SaveChanges();
        }
        public Task UpdateAsync(TEntity entity, bool isSave = true)
        {
            if (isSave)
                return _dbContext.SaveChangesAsync();
            return nullTask;
        }
    }

}
